import json
import copy
from typing import List
from typing import Union
from apis import api_routes
from sqlalchemy import desc
from sqlalchemy import and_
from flask import abort, g, request, jsonify
from models.users.roles import Roles as Rs
from models.users.users import Users as Us
from models.owner.owner import Owner
from security.decoration import certification
from public.sidebar import sidebars
from public.contexts import context_logs
from datetime import datetime
from public.local import local_date
from public.local import datetime_type
from models.facility.facility import Facility
from models.owner.entering import Entering


@api_routes.route("/entering", methods=["GET"])
@certification(auth=True, role="admin")
def func_entering_get_api():
    """
    查询工站信息
    http://127.0.0.1:8080/api/entering
    Content-Type=application/json
    methods=["GET"]
    :return:
     ---
    tags:
      - 信息录入
    """
    reps: list = []
    db_data: List[Entering] = g.session.query(Entering).order_by(Entering.facility_id).all()
    for index, itr in enumerate(db_data):
        facility: Facility = g.session.query(Facility).filter(Facility.id == itr.facility_id).first()
        reps.append({
            "entering_id": itr.id,
            "serials": facility.serials,
            "name": facility.name,
            "option": itr.option,
            "code": itr.code,
            "enable": itr.enable
        })
    docs: dict = {
        "serials": "设备编号",
        "name": "设备名称",
        "option": "操作员信息",
        "code": "物料码",
        "enable": "是否可以编辑 code "
    }
    return jsonify({'status': 200, "data": reps, "docs": docs})


@api_routes.route("/entering", methods=["PUT"])
@certification(auth=True, role="admin")
def func_entering_put_api():
    """
    更改信息
    http://127.0.0.1:8080/api/entering
    Content-Type=application/json
    methods=["GET"]
    {
    "entering_id":   int        ****    数据库ID
    "option":       string           操作用户
    "code"       string            物料码
    }
    :return:
     ---
    tags:
      - 信息录入
    """
    data: dict = request.get_json()
    entering_id: Union[int, None] = data.get("entering_id")
    option: Union[int, None] = data.get("option")
    code: Union[int, None] = data.get("code")

    if entering_id is None:
        abort(400)
    db_entering: Union[Entering, None] = g.session.query(Entering).filter(Entering.id == entering_id).first()
    if db_entering is None:
        return jsonify({'status': 4000, 'data': "没有找到信息"})
    if option is not None and len(str(option)) > 0:
        db_entering.option = option
    if code is not None and len(str(code)) > 0 and db_entering.enable is True:
        db_entering.code = code
    elif db_entering.enable is False:
        db_entering.code = None

    g.session.commit()
    return jsonify({'status': 200, "msg": "成功"})
